package com.whmskj.xjlhbc.mobile.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.domain.DictionaryProcess;
import com.whmskj.xjlhbc.mapper.DictionaryProcessMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;

@RestController
@Tag(name = "文件上传",description = "文件上传")
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private DictionaryProcessMapper dictionaryProcessMapper;

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @Operation(description = "文件上传",parameters = @Parameter(name = "file",description = "文件"))
    public AjaxResult uploadFile(MultipartFile file){
        try {
            String filePath = "upload";
            String fileName = upload(filePath, file);
            String url = "http://171.35.137.182:8082/api/"+fileName;
            return AjaxResult.success("上传成功",url);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查字典表
     */
    @GetMapping("/getDataDictionary")
    @Operation(description = "查字典表",parameters = @Parameter(name = "code",description = "编码,维保项目:Main-project,故障类型:Fault-type"))
    public AjaxResult getDataDictionary(String code){
        LambdaQueryWrapper<DictionaryProcess> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DictionaryProcess::getDictionaryEncoding, code);
        List<DictionaryProcess> list = dictionaryProcessMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    private static String upload(String baseDir, MultipartFile file)
            throws  IOException
    {
        String fileName = file.getOriginalFilename();
        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        return "/profile/" + fileName;
    }

    private static File getAbsoluteFile(String uploadDir, String fileName){
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.exists()){
            if (!desc.getParentFile().exists()){
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }

}
